package com.imclient.headler;

import com.imclient.message.Header;
import com.imclient.message.Message;
import com.imclient.server.HeadlerServer;
import com.imclient.type.ConnInfoType;
import com.imclient.type.HeaderType;
import com.imclient.type.PushType;

public class LoginHeadler extends AbstractHeadler{

	
	private String username ;
	
	private String  password  ;
	
	private long keeplive = 60000;
	
	public LoginHeadler(String username,String password){
		this.username = username;
		this.password = password;
		
	}
	
	@Override
	public PushType getPushType() {
		return PushType.LOGIN;
	}
	
	private boolean live = true;
	
	
	
	
	public void setKeeplive(long keeplive) {
		this.keeplive = keeplive;
	}

	private void live(final HeadlerServer hs){
		
		new Thread(){
			
			public void run() {
				if(!live){
					return;
				}
				while(true){
					if(hs.isMclose()){
						break;
					}
					live = false;
					if(!hs.isIsretry()){
						live = true;
						break;
					}else{
						try {
							hs.setKeeplive(keeplive);
							Message live = new Message();
							Header[] headers = new Header[]{new Header(HeaderType.Type.name(),PushType.LIVE.name())};
							live.setHeaders(headers);
							hs.SendMsg(live);
							Thread.sleep(keeplive);
						} catch (Exception e) {
							e.printStackTrace();
						}finally{}
					}
					
				}
				
				
			};
			
		}.start();
		
	}
	

	@Override
	public void netBreak() {
		live = false;
	}

	@Override
	public void receive(Message msg, HeadlerServer hs) {
		
		String value = msg.getHeader(HeaderType.Status.name());
		if(value.equals(PushType.START.name())){
			Message login = new Message();
			Header[] headers = new Header[]{new Header(HeaderType.Type.name(),PushType.LOGIN.name()),new Header(HeaderType.Username.name(),username),new Header(HeaderType.Password.name(),password),new Header(HeaderType.Time.name(),String.valueOf(keeplive))};
			login.setHeaders(headers);
			hs.setIsretry(false);
			hs.SendMsg(login);
			hs.connectInfo(ConnInfoType.STARTLOGIN);
		}
		if(value.equals(PushType.SUCCESS.name())){
			hs.setIsretry(true);
			live = true;
			live(hs);
			hs.connectInfo(ConnInfoType.LOGINSUCCESS);
		}
		
		if(value.equals(PushType.LOGOUT.name())){
			live = false;
			hs.setIsretry(false);
			hs.close();
			hs.connectInfo(ConnInfoType.LOGOUT);
		}
		
		
	}

}
